package com.aixuexiao.web.controller;


import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.aixuexiao.model.Classes;
import com.aixuexiao.model.Setting;
import com.aixuexiao.model.Student;
import com.aixuexiao.service.ClassesService;
import com.aixuexiao.service.SettingService;
import com.aixuexiao.service.StudentService;
import com.weixin.sdk.util.MessageUtil;

@Controller()
public class LoginController {
	@Resource(name="studentService")
	private StudentService studentService;
	@Resource(name="settingService")
	private SettingService settingService;
	@Resource(name="classesService")
	private ClassesService classesService;
	/**
	微信配置地址配置为:appid,redirect_uri(m=Weixin&a=login&token)是需要修改的
	https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2bd1aabfdac9f3c9&redirect_uri=http://chongxinsay.xyz/employee?m=Weixin&token=ESS9paEHszg7j2Gidfry&response_type=code&scope=snsapi_base&state=1#wechat_redirect
	 * @throws IOException 
	**/
	@RequestMapping("/")
	public String index(HttpServletRequest request) {
		
		//验证是否是微信接入
		String openId = MessageUtil.getWeixinOpenId(request);
		if(!StringUtils.isEmpty(openId)){
			//查询出对应的用户
			Student student = studentService.findStudentByOpenId(openId);
			if(student!=null && openId.equals(student.getOpenid())){//跳转到认证成功页面
				request.setAttribute("message", "员工（"+student.getName()+"）已认证");
				request.setAttribute("student", student);
				return "sucess";
			}
			return "login";
		}else{
			return "loginPc";
		}
	}
	
	@RequestMapping(value="/loginPc",method=RequestMethod.POST)
	public ModelAndView loginPc(String username,String password,HttpServletRequest request){
		ModelAndView mv=new ModelAndView("");
		Setting setting = settingService.isAdministrator(username);
		if(setting!=null&& setting.getPassword().equals(password)){//用户名密码正确
			request.getSession().setAttribute("user", username);
			mv.setViewName("redirect:/manager/students");
		}else if(setting!=null){
			mv.setViewName("forward:/");
			mv.addObject("username",username);
			mv.addObject("message", "管理员密码错误！");
		}else{
			mv.setViewName("forward:/");
			mv.addObject("username",username);
			mv.addObject("message", "管理员账号错误！");
		}
		return mv;
	}
	/**
	微信配置地址配置为:appid,redirect_uri(m=Weixin&token=)是需要修改的
	https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8888888888888888&redirect_uri=http://chongxinsay.xyz/employee/companydes?m=Weixin&token=frbeev1454049984&response_type=code&scope=snsapi_base&state=1#wechat_redirect
	*/
	@RequestMapping(value="/companyclub")
	public ModelAndView companydes(HttpServletRequest request){
		ModelAndView mv=new ModelAndView("");
		String openId = MessageUtil.getWeixinOpenId(request);
		Student student = null;
		if(!StringUtils.isEmpty(openId)){
			student = studentService.findStudentByOpenId(openId);
			if(student!=null){
				mv.setViewName("redirect:http://www.henro.cn/index.php?g=Wap&m=Index&a=content&token=frbeev1454049984&id=4027");
			}else{
				mv.setViewName("forward:/");
				mv.addObject("message", "您好，您还未认证！");
			}
		}else{
			mv.setViewName("forward:/");
			mv.addObject("message", "您好，您还未认证！");
		}
		return mv;
	}
	@RequestMapping(value="/login")
	public ModelAndView login(String username,String password,HttpServletRequest request){
		ModelAndView mv=new ModelAndView("");
		try{
			String openid = MessageUtil.getWeixinOpenId(request);
			Student student = studentService.findStudentById(Integer.parseInt(username));
			if(student!=null && password.equals(student.getPassword())){//用户名密码正确直接进入认证页面
				mv.addObject("message", "员工（"+student.getName()+"）已认证");
				student.setOpenid(openid);
				classesService.updateStudentBy(student);//更新微信标示
				mv.setViewName("sucess");
			}else if(student!=null && !StringUtils.isEmpty(student.getPassword())){//用户名密码不匹配
				mv.setViewName("forward:/");
				mv.addObject("username",username);
				mv.addObject("message", "用户名密码错误！");
			}else{//员工不存在但是或用户未认证过
				request.getSession().setAttribute("user", username);
				mv.setViewName("forward:/");
				mv.addObject("message", "您还未认证，请先注册！");
			}
		}catch(Exception e){
			e.printStackTrace();
			mv.setViewName("forward:/");
			mv.addObject("message", "请输入数字工号！");
		}
		return mv;
	}
	/**
	 * 微信账号解绑
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/jiebang")
	public ModelAndView jiebang(String id,HttpServletRequest request){
		ModelAndView mv=new ModelAndView("");
		try{
			int stuId = Integer.parseInt(id);
			Student student = studentService.findStudentById(stuId);
			if(student!=null){
				studentService.removeStudentOpenId(stuId);
			}else{
				throw new RuntimeException();
			}
			mv.addObject("message", "取消认证成功,如需认证，请登录！");
			mv.setViewName("sucess1");
		}catch(Exception e){
			e.printStackTrace();
			mv.setViewName("sucess");
			mv.addObject("message", "操作失败！");
		}
		return mv;
	}
	@RequestMapping(value="/register")
	public ModelAndView register(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("register");
		List<Classes> clslist = studentService.findAllClasses();
		mv.addObject("clsList", clslist);
		String openid = MessageUtil.getWeixinOpenId(request);
		if(!StringUtils.isEmpty(openid))
			mv.addObject("openid",openid);
		return mv;
	}
	@RequestMapping(value="/register/studentAdd")
	public ModelAndView userAdd(HttpServletRequest request,Student student){
		ModelAndView mv=new ModelAndView();
		Student s_student = new Student();
		s_student.setId(student.getId());
		s_student.setClassid(student.getClassid());
		s_student.setName(student.getName());
		List<Student> list = studentService.listStudent(0, 1, s_student);
		if(list!=null && list.size()>0){//员工存在时，关联openid或unionid不添加
			classesService.updateStudentBy(student);
			classesService.updateClassStudentCount(student.getClassid());
			request.getSession().setAttribute("notice","员工("+student.getName()+")认证成功!");
			mv.setViewName("redirect:/");
		}else{
			request.getSession().setAttribute("notice","系统暂未找到匹配的员工信息（请确保工号、公司、名称无误）！");
			mv.setViewName("redirect:/register");
		}
		return mv;
	}
	@RequestMapping(value="/loginout")
	public ModelAndView loginOut(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("forward:/");
		request.getSession().removeAttribute("user");
		return mv;
	}
	@RequestMapping(value="/manager/updateAdministrator",method=RequestMethod.POST)
	public ModelAndView updateAdministrator(String username,String password,String newpassword,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		Setting setting = settingService.isAdministrator(username);
		if(setting==null){//用户找不到，数据异常管理员被临时删除
			throw new RuntimeException("账号错误");
		}else if(setting !=null && password.equals(setting.getPassword())){//管理员修改密码成功
			mv.setViewName("redirect:/index");
			setting.setPassword(newpassword);
			settingService.updateAdministrator(setting);
			request.setAttribute("message","密码修改成功，请重新登陆！");
			request.getSession().removeAttribute("user");
		}else{//管理员输入密码不匹配
			mv.setViewName("redirect:/manager/students");
			mv.addObject("passwdmsg","输入的原密码不正确，请重新输入！");
		}
		return mv;
	}
}
